package com.wenwu.controller.unmovable;

import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONArray;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.codehaus.jackson.JsonGenerator;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.wenwu.common.bean.FileUtils;
import com.wenwu.common.bean.RelicsAttachment;
import com.wenwu.common.bean.RelicsOrganization;
import com.wenwu.common.bean.RelicsProtectArea;
import com.wenwu.common.bean.RelicsProtectBasic;
import com.wenwu.common.exception.RelicsException;
import com.wenwu.common.page.PageUtils;
import com.wenwu.common.page.PaginationVO;
import com.wenwu.common.utils.JsonUtils;
import com.wenwu.common.utils.ReflectBeanUtils;
import com.wenwu.common.utils.Status.AttachmentFrom;
import com.wenwu.service.CommonService;
import com.wenwu.service.OrganizationService;
import com.wenwu.service.ProtectAreaService;

/**
 * 保护区划以及保护情况
 * 
 * @author LINHAI
 *
 */
@Controller(value = "ProtectAreaAndConditionController")
@RequestMapping(value = "/mgr/protectArea")
public class ProtectAreaAndConditionController {

	@Autowired
	private ProtectAreaService protectAreaService;
	@Autowired
	private CommonService commonService;
	@Autowired
	OrganizationService organizationService;

	// Json数据传输
	private JsonGenerator jsonGenerator = null;
	Logger log = Logger.getLogger(this.getClass());

	@RequestMapping(value = "/init")
	public String initProtectSatuPage() {
		log.info("进入保存现状的页面");
		return "umprotectarea/umprotectarealist";
	}

	@RequestMapping(value = "/umprotectAreaForm")
	public String dictionaryform(Model model,
			@RequestParam(required = false, value = "basicId") Integer basicId,
			@RequestParam(required = false, value = "name") String name)
			throws Exception {
		log.info("进入表单页面...");
		try {
			if (StringUtils.isNotBlank(name)) {
				model.addAttribute("name", URLDecoder.decode(name, "UTF-8"));
			}
			if (basicId != null) {// 查询对应的附件集合
				List<RelicsAttachment> attachments = commonService
						.selectAttachmentListByKey(basicId,
								"relics_protect_area", "protect_id",
								"basic_id",
								AttachmentFrom.RELICS_PROTECT_AREA_01);
				model.addAttribute("attachments", attachments);
				RelicsProtectArea relicsProtectArea = protectAreaService
						.selectProtectAreaByBasicId(basicId);
				model.addAttribute("relicsProtectArea", relicsProtectArea);
				if (relicsProtectArea != null) {
					List<Integer> keys = new ArrayList<Integer>();
					keys.add(relicsProtectArea.getProtectBasicId());
					keys.add(relicsProtectArea.getControlArea());
					keys.add(relicsProtectArea.getProtectArea());
					List<RelicsProtectBasic> blist = protectAreaService
							.selectProtectBasicList(keys);
					if (blist != null && blist.size() > 0) {
						for (RelicsProtectBasic rpb : blist) {
							if (rpb.getProtectBasicId().equals(
									relicsProtectArea.getProtectBasicId())) {
								model.addAttribute("rpb1", rpb);
							} else if (rpb.getProtectBasicId().equals(
									relicsProtectArea.getProtectArea())) {
								model.addAttribute("rpb2", rpb);
							} else if (rpb.getProtectBasicId().equals(
									relicsProtectArea.getControlArea())) {
								model.addAttribute("rpb3", rpb);
							}
						}
					}
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return "umprotectarea/umprotectareaform";
	}

	@SuppressWarnings("unchecked")
	@RequestMapping(value = "/addObj")
	public void addObj(@RequestParam(value = "data") String data,
			@RequestParam(value = "ortherData") String ortherData,
			HttpServletResponse response) throws Exception {
		log.info("添加文物区划");
		log.info(data);
		jsonGenerator = JsonUtils.getJsonGenerator(response);
		FileUtils fs=new FileUtils();
		HashMap<String, String> map=ReflectBeanUtils.creatMap(data);
		//获取附件集合
		List<RelicsAttachment> ralist=fs.getFileListByString(map.get("filePaths"), map.get("fileNames"), map.get("attachmentOwners"));
		RelicsProtectArea relicsProtectArea = null;
		List<RelicsProtectBasic> list = null;
		try {
			if (StringUtils.isNotBlank(data)) {
				relicsProtectArea = (RelicsProtectArea) ReflectBeanUtils
						.getObject(data, RelicsProtectArea.class);
			}
			if (StringUtils.isNotBlank(ortherData)) {
				log.info("RelicsProtectBasic:" + ortherData);
				JSONArray array = null;
				array = JSONArray.fromObject(ortherData);
				list = (List<RelicsProtectBasic>) JSONArray.toCollection(array,
						RelicsProtectBasic.class);
				log.info("获得List<RelicsProtectBasic>.size=" + list.size());
			}
			int result = protectAreaService.saveData(relicsProtectArea, list,ralist);
			if (result > 0) {
				jsonGenerator.writeObject("保存成功");
			} else {
				jsonGenerator.writeObject("保存失败");
			}
		} catch (Exception e) {
			e.printStackTrace();
			jsonGenerator.writeObject("系统异常");
		}
	}

	@RequestMapping(value = "/showUpdate")
	public @ResponseBody RelicsProtectArea selectProtectAreaByBasicId(
			@RequestParam(required = false, value = "basicId") Integer basicId) {
		RelicsProtectArea relicsProtectArea = null;
		log.debug("获得保存现状查询主键basicId===" + basicId);
		if (basicId != null) {
			try {
				relicsProtectArea = protectAreaService
						.selectProtectAreaByBasicId(basicId);
			} catch (RelicsException e) {
				e.printStackTrace();
			}
		}
		return relicsProtectArea;

	}

	@RequestMapping(value = "/showThisUpdate")
	public @ResponseBody RelicsProtectArea showThisUpdate(
			@RequestParam(required = false, value = "protectId") Integer protectId)
			throws Exception {
		RelicsProtectArea relicsProtectArea = null;
		try {
			if (protectId != null) {
				relicsProtectArea = protectAreaService
						.selectProtectAreaByProtectId(protectId);
			}
		} catch (Exception e) {
		}
		return relicsProtectArea;
	}

	@RequestMapping(value = "/showList")
	public @ResponseBody PaginationVO showList(
			RelicsProtectArea relicsProtectArea, HttpServletRequest request)
			throws Exception {
		PaginationVO pageVo = null;
		try {
			pageVo = PageUtils.getPaginationInfo(request);
			pageVo = protectAreaService.selectList(relicsProtectArea, pageVo);// 查询符合条件的数据
		} catch (Exception e) {
		}
		return pageVo;
	}

	@RequestMapping(value = "/deleteInfo")
	public void deleteInfo(HttpServletResponse response,
			HttpServletRequest request,
			@RequestParam(required = false, value = "key") String key)
			throws Exception {
		log.info("主键：" + key);
		if (key != null) {
			List<String> keys = new ArrayList<String>();
			String[] objs = key.split(",");
			for (String k : objs) {
				keys.add(k);
			}
			jsonGenerator = JsonUtils.getJsonGenerator(response);
			try {
				int result = protectAreaService.deleteByKey(keys);
				jsonGenerator.writeObject("成功删除" + result + "条数据");
			} catch (Exception e) {
				jsonGenerator.writeObject("删除数据失败");
			}
		}
	}
	// RelicsOrganization
	@RequestMapping(value = "/getRelicsOrganization")
	public @ResponseBody List<RelicsOrganization> getRelicsOrganization()
			throws Exception {
		return organizationService.selectAllOrganization();
	}
}
